package com.imooc.luckymoney.controller;

import com.imooc.luckymoney.dao.LuckymoneyRepository;
import com.imooc.luckymoney.model.Luckymoney;
import com.imooc.luckymoney.service.LuckymoneyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@RestController
public class LuckymoneyController {

    @Autowired
    private LuckymoneyRepository repository;

    @Autowired
    private LuckymoneyService service;

    @GetMapping("/luckymoneys")
    public List<Luckymoney> list(){
        return repository.findAll();
    }

    @PostMapping("/luckymoneys")
    public Luckymoney save(@RequestParam("producer") String producer,
                           @RequestParam("money")BigDecimal money){

        Luckymoney luckymoney = new Luckymoney();
        luckymoney.setProducer(producer);
        luckymoney.setMoney(money);
//        luckymoney.setConsumer();

        return repository.save(luckymoney);
    }


    /**
     * 表单数据验证（大于1元）
     * 在model中的字段中添加注解 @Min(value = 1,message = "红包至少要大于1元")
     */
    @PostMapping("/insert")
    public Luckymoney insert(@Valid Luckymoney luckymoney, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            //打印错误信息
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            return null;
        }

        Luckymoney temp = new Luckymoney();
        temp.setProducer(luckymoney.getProducer());
        temp.setMoney(luckymoney.getMoney());

        return repository.save(temp);
    }

    @GetMapping("/luckymoneys/{id}")
    public Luckymoney findById(@PathVariable("id") Integer id){
        return repository.findById(id).orElse(null);
    }

    @PostMapping("/luckymoneys/{id}")
    public Luckymoney update(@PathVariable("id") Integer id,
                             @RequestParam("consumer") String consumer){
        Optional<Luckymoney> optional = repository.findById(id);
        //判断是否有这条数据
        if (optional.isPresent()){
            Luckymoney luckymoney = optional.get();
            luckymoney.setConsumer(consumer);
            return repository.save(luckymoney);
        }
        return null;
    }

    @PostMapping("/luckymoney/two")
    public void createTwo(){
        service.createTwo();
    }


}
